#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstdint>
#include <sys/timerfd.h>
int main()
{
    int timerfd = timerfd_create(CLOCK_MONOTONIC, 0);
    if(timerfd < 0)//assert
    {
        perror("timefd_create error");
    }
    struct itimerspec itime;
    itime.it_value.tv_sec = 5;//First timeout time,3 seconds.
    itime.it_value.tv_nsec = 0;//Prevent random numbers and set the time to zero.
    itime.it_interval.tv_sec = 5;//After the first timeout, the time for subsequent timeouts,3 seconds.
    itime.it_interval.tv_nsec = 0;
    if (-1 == timerfd_settime(timerfd, 0, &itime, nullptr)) 
    {
        perror("timerfd_settime error");
    }
    while(1)
    {
        int a=0;
        std::cin >> a;
        if(a!=0)
        {
            itime.it_value.tv_sec = 5;//First timeout time,3 seconds.
            itime.it_value.tv_nsec = 0;//Prevent random numbers and set the time to zero.
            itime.it_interval.tv_sec = 5;//After the first timeout, the time for subsequent timeouts,3 seconds.
            itime.it_interval.tv_nsec = 0;
            if (-1 == timerfd_settime(timerfd, 0, &itime, nullptr)) 
            {
                perror("timerfd_settime error");
            }
        }
        uint64_t timesBuffer;//从文件描述符timerfd中读取超时了多少次
        if(-1 == read(timerfd, &timesBuffer, sizeof(timesBuffer)))//一般是阻塞住。while循环很快，一有数据马上读掉
        {
            perror("timefd read error\n");
        }
        else
        {
            printf("超时了，距离上一次超时了%ld次\n", timesBuffer);
        }
    }
    close(timerfd);
    return 0;
}
 